<template>
	<el-dialog
	  :title="isUpdate ? '修改' : '放行'"
	  :visible.sync="visible"
	  :before-close="close"
	  :close-on-click-modal="false"
	  width="40%">

    <el-card>
      <el-form label-position="right" label-width="100px">
        <el-form-item label="请验类型:">
          {{ dataForm.checkTypeName }}
        </el-form-item>

        <el-form-item label="货品名称:">
          {{ dataForm.productName }}
        </el-form-item>

        <el-form-item label="货品规格:">
          <span v-html="(dataForm.productSpec != null && dataForm.productSpec != '') ? dataForm.productSpec : '无'" />
        </el-form-item>

        <el-form-item label="物料编码:">
          {{ dataForm.productGmp }}
        </el-form-item>

        <el-form-item>
          <span slot="label">批&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</span>
          {{ dataForm.batchNum }}
        </el-form-item>

        <el-form-item label="检验单号:">
          {{ dataForm.checkNum }}
        </el-form-item>

        <el-form-item label="生产日期:">
          {{ dataForm.productionDate | changeTime }}
        </el-form-item>

        <el-form-item v-if="yfb">
          <span slot="label">车&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;间:</span>
          <el-select v-model="dataForm.workshopName" filterable placeholder="车间" size="small" style="width: 100%">
            <el-option
              v-for="item in workshopList"
              :key="item.workshopId"
              :label="item.workshopName"
              :value="item.workshopName">
            </el-option>
          </el-select>
        </el-form-item>

        <div v-if="dataForm.validityDate != null">
          <el-form-item v-if="dataForm.productionDate != null">
            <span slot="label">有&nbsp;&nbsp;效&nbsp;&nbsp;期:</span>
            {{ dataForm.validity + ' 月'}}
          </el-form-item>

          <el-form-item label="有效期至:">
            <el-date-picker
              v-model="dataForm.validityDate"
              align="right"
              type="date"
              placeholder="选择日期"
              @change="setValidity"
              style="width: 100%;"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small">
            </el-date-picker>
          </el-form-item>
        </div>
        <div v-if="dataForm.reinspectDate != null">
          <el-form-item v-if="dataForm.productionDate != null">
            <span slot="label">复&nbsp;&nbsp;验&nbsp;&nbsp;期:</span>
            {{ dataForm.reinspect + ' 月'}}
          </el-form-item>

          <el-form-item label="复验时间:">
            <el-date-picker
              v-model="dataForm.reinspectDate"
              align="right"
              type="date"
              placeholder="选择日期"
              @change="setReinspect"
              style="width: 100%;"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd HH:mm:ss"
              size="small">
            </el-date-picker>
          </el-form-item>
        </div>

        <el-form-item label="包装规格:">
          <div>
            <span>{{ dataForm.productPackSpecShow }}</span>
            <el-button class="pan-btn warning-btn" type="warning" @click="showMaintainPackSpec" size="small">去删除多余的包装规格</el-button>
          </div>
          <el-input v-if="addFullSpec" v-model="dataForm.productPackSpec" style="width: 90%;" placeholder="包装规格" size="small" />
          <el-select v-else v-model="dataForm.productPackSpec" placeholder="包装规格" style="width: 90%;" size="small">
            <el-option v-for="item in productFullSpecList" :key="item.productFullSpecId" :label="item.productFullSpec" :value="item.productFullSpec" />
          </el-select>
          <el-tooltip :content="addFullSpec ? '选择列表' : '新增一个'" placement="top">
            <el-switch
              v-model="addFullSpec"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @click.native="changeFullSpecFlag()">
            </el-switch>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="不放行数量:">
          <el-input v-model="dataForm.noPassQuantity" placeholder="不放行数量" size="small">
            <el-select value-key="unitId" v-model="dataForm.passUnit" @change="setPassUnit" slot="append" placeholder="单位" style="width: 100px;">
              <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
            </el-select>
          </el-input>
        </el-form-item>

        <el-form-item label="放行数量:">
          <el-input v-model="dataForm.passQuantity" placeholder="放行数量" size="small">
            <el-select value-key="unitId" v-model="dataForm.passUnit" @change="setPassUnit" slot="append" placeholder="单位" style="width: 100px;">
              <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item" />
            </el-select>
          </el-input>
        </el-form-item>

        <el-form-item label="放行日期:">
          <el-date-picker
            v-model="dataForm.passDate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            style="width: 100%;"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd HH:mm:ss"
            size="small">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="特殊情况:">
          <el-input placeholder="特殊情况" v-model="dataForm.exceptionRemark" clearable size="small" />
        </el-form-item>

        <el-form-item label="退换货等:">
          <el-input placeholder="退换货等" v-model="dataForm.improperPassRemark" clearable size="small" />
        </el-form-item>

        <el-form-item label="备注:">
          <span slot="label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注:</span>
          <el-input placeholder="备注" v-model="dataForm.remark" clearable size="small" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog
      title="维护包装规格"
      :visible.sync="maintainPackSpecVisible"
      append-to-body
      width="30%">
      <el-table :data="allFullSpecList">
        <el-table-column prop="productFullSpec"></el-table-column>\
        <el-table-column>
          <template slot-scope="scope">
            <el-button @click="deleteFullSpec(scope.$index)" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

	  <span slot="footer" class="dialog-footer">
      <el-button @click="close" size="small">取 消</el-button>
      <el-button class="pan-btn primary-btn" type="primary" :loading="submiting" @click="submit" size="small">确 定</el-button>
  	</span>

	</el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getUnitList,pass,getPassInfo,getFullSpec,getPass,deleteFullSpec,getWorkshopList } from '@/api/check'
  import { CODE_OK } from '@/common/js/config'
  import { isBlank,parseTime } from '@/common/js/utils'
  import { isPositiveNumber } from '@/common/js/validate'
  export default {
  	data() {
  		return {
        unitList: [],
        allFullSpecList: [],
        productFullSpecList: [],
        addFullSpec: false,
  			visible: false,
        submiting: false,
        dataForm: {},
        showCheckList: {},
        mainCheckList: {},
        yfbList: {},
        zcList: {},
        isUpdate: false,
        maintainPackSpecVisible: false,
        workshopList: []
  		}
  	},
  	props: ["childDataForm"],
  	created() {
  		if (!isBlank(this.childDataForm)) {
        this.showCheckList = this.childDataForm
        this.isUpdate = this.showCheckList.status > 7
        this.getInfo()
        this.visible = true
  		}
  	},
    computed: {
      ...mapGetters([
         'userInfo'
      ]),
      yfb() {
        return this.showCheckList.checkTypeName == '原料' || this.showCheckList.checkTypeName == '辅料' || this.showCheckList.checkTypeName == '包材' || this.showCheckList.checkTypeName == '其他'
      },
      zc() {
        return this.showCheckList.checkTypeName == '中间品' || this.showCheckList.checkTypeName == '成品'
      }
    },
  	methods: {
      deleteFullSpec(i) {
        deleteFullSpec(this.allFullSpecList[i].productFullSpecId).then(res => {
          if (res.code === CODE_OK) {
            this.allFullSpecList.splice(i,1)
            this.productFullSpecList.splice(i,1)
            // let arr = this.allFullSpecList.filter(p => {
            //   return p.productFullSpec.indexOf(this.dataForm.productPackSpecShow) > -1
            // })
            // this.productFullSpecList = arr.length == 0 ? this.allFullSpecList : arr
            this.$message.success('删除成功')
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      showMaintainPackSpec() {
        if (this.allFullSpecList.length == 0) {
          this.$message.error('本货品无完整包装规格，请先添加')
        }else{
          this.maintainPackSpecVisible = true
        }
      },
      changeFullSpecFlag() {
        if (this.productFullSpecList.length == 0) {
          this.$message.error("此货品无完整包装规格,请添加")
          this.addFullSpec = true
        }
      },
      init() {
        this.dataForm = this.mainCheckList
        this.dataForm.productPackSpecShow = JSON.parse(JSON.stringify(this.dataForm.productPackSpec))
        this.dataForm.productPackSpec = ''
        // 不根据请验单上的包装规格过滤
        // if (this.productFullSpecList.length != 0) {
        //   let arr = this.productFullSpecList.filter(p => {
        //     return p.productFullSpec.indexOf(this.dataForm.productPackSpecShow) > -1
        //   })
        //   this.productFullSpecList = arr.length == 0 ? this.productFullSpecList : arr
        // }
        this.$set(this.dataForm,'passUserId', this.userInfo.userId)
        this.$set(this.dataForm,'passUserName', this.userInfo.name)
        this.$set(this.dataForm,'passDate', '')
      },
      getInfo() {
        if (this.yfb) {
          getWorkshopList().then(res => {
            if (res.code === CODE_OK) {
              this.workshopList = res.list
            }else{
              this.$message.error(res.msg)
            }
          })
        }
        getUnitList().then(res => {
          if (res.code === CODE_OK) {
            this.unitList = res.list
          }else{
            this.$message.error(res.msg)
          }
        })
        const params1 = {
          productId: this.showCheckList.productId
        }
        getFullSpec(params1).then(res => {
          if (res.code === CODE_OK) {
            this.allFullSpecList = res.list
            this.productFullSpecList = JSON.parse(JSON.stringify(this.allFullSpecList))
            if (this.productFullSpecList.length == 0) {
              this.addFullSpec = true
            }
          }else{
            this.$message.error(res.msg)
          }
        })
        const params2 = {
          checkTypeName: this.showCheckList.checkTypeName,
          checkMergeId: this.showCheckList.checkMergeId,
          content: this.yfb ? 'yfb' : 'zc',
          productId: this.showCheckList.productId
        }
        if(this.isUpdate){
          getPass(params2).then(res => {
            if (res.code === CODE_OK) {
              this.dataForm = res.pass
              this.$set(this.dataForm,'passUnit',{
                unitId: this.dataForm.passUnitId,
                unitName: this.dataForm.passUnitName
              })
            }else{
              this.$message.error(res.msg)
            }
          })
        }else{
          getPassInfo(params2).then(res => {
            if (res.code === CODE_OK) {
              this.yfbList = res.info.yfbList
              this.zcList = res.info.zcList
              if (this.zc) {
                this.mainCheckList = res.info.list
                this.mainCheckList.checkMergeId = this.showCheckList.checkMergeId
                this.mainCheckList.registCheckDate = this.showCheckList.registCheckDate
                this.$set(this.mainCheckList,'productionDate', this.zcList.productionDate)
                this.$set(this.mainCheckList,'validityDate', this.zcList.validityDate)
                this.$set(this.mainCheckList,'validity', this.monDiff(this.mainCheckList.productionDate, this.mainCheckList.validityDate))
                this.$set(this.mainCheckList,'batchQuantity', this.zcList.batchQuantity)
                this.$set(this.mainCheckList,'batchUnitId', this.zcList.batchUnitId)
                this.$set(this.mainCheckList,'batchUnitName', this.zcList.batchUnitName)
              }else if(this.yfb) {
                this.mainCheckList = this.showCheckList
                this.$set(this.mainCheckList,'productionDate', this.yfbList.productionDate)
                this.$set(this.mainCheckList,'originalBatch', this.yfbList.originalBatch)
                if (!isBlank(this.yfbList.validityDate)) {
                  this.$set(this.mainCheckList,'validityDate', this.yfbList.validityDate)
                  this.$set(this.mainCheckList,'validity', this.monDiff(this.mainCheckList.productionDate, this.mainCheckList.validityDate))
                }else{
                  this.$set(this.mainCheckList,'reinspectDate', this.yfbList.reinspectDate)
                  this.$set(this.mainCheckList,'reinspect', this.monDiff(this.mainCheckList.productionDate, this.mainCheckList.reinspectDate))
                }
                this.$set(this.mainCheckList,'grossPiece', this.yfbList.grossPiece)
                this.$set(this.mainCheckList,'grossQuantity', this.yfbList.grossQuantity)
                this.$set(this.mainCheckList,'grossUnitId', this.yfbList.grossUnitId)
                this.$set(this.mainCheckList,'grossUnitName', this.yfbList.grossUnitName)
                this.$set(this.mainCheckList,'manufacturerId', this.yfbList.manufacturerId)
                this.$set(this.mainCheckList,'manufacturerName', this.yfbList.manufacturerName)
                this.$set(this.mainCheckList,'supplierId', this.yfbList.supplierId)
                this.$set(this.mainCheckList,'supplierName', this.yfbList.supplierName)
                this.$set(this.mainCheckList,'workshopName', !isBlank(res.info.lastPass) ? res.info.lastPass.workshopName : null)
              }
              this.init()
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
  		close(val) {
  			this.$emit('close')
  			if (val == 'submit') {
  			  this.$emit('refreshData')
  			}
  			this.visible = false
  		},
  		submit() {
        this.submiting = true
        if (!this.isUpdate) {
          this.dataForm.addFullSpec = this.addFullSpec
        }else{
          this.dataForm.addFullSpec = false
        }
        if (this.formVerify()) {
          pass(this.dataForm).then(res => {
            if (res.code === CODE_OK) {
              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 3500
              })
              this.close('submit')
            }else{
              this.$message.error(res.msg)
            }
            this.submiting = false
          })
        }else{
          this.submiting = false
        }
      },
      formVerify() {
        if (isBlank(this.dataForm.productPackSpec)) {
          this.$message.error('请填写包装规格')
          return false
        }
        if (isBlank(this.dataForm.passQuantity) && isBlank(this.dataForm.noPassQuantity)) {
          this.$message.error('请输入放行(或不放行)数量')
          return false
        }
        if (isBlank(this.dataForm.passUnitId)) {
          this.$message.error('请选择放行数量单位')
          return false
        }
        if (isBlank(this.dataForm.passDate)) {
          this.$message.error('请选择放行日期')
          return false
        }
        return true
      },
      setValidity() {
        this.dataForm.validity = this.monDiff(this.dataForm.productionDate, this.dataForm.validityDate)
      },
      setReinspect() {
        this.dataForm.reinspect = this.monDiff(this.dataForm.productionDate, this.dataForm.reinspectDate)
      },
      setPassUnit() {
        this.dataForm.passUnitId = this.dataForm.passUnit.unitId
        this.dataForm.passUnitName = this.dataForm.passUnit.unitName
      },
      monDiff(startTime, endTime) {
        if (isBlank(startTime) || isBlank(endTime)) return 0
        let e = this.moment(endTime.split(' ')[0]).add(1, 'd')
        let s = this.moment(startTime.split(' ')[0])
        return e.diff(s, 'M')
      }
    }
  }
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: 40px !important;
  }
  .el-form-item {
    margin-bottom: 0px !important;
  }
  .el-form-item__content .el-input-group {
    vertical-align: inherit !important;
  }
</style>
